<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>boostrap-框架-综合案例</title>
  <!-- 1 引入它的css -->
  <link rel="stylesheet" href="./lib/bootstrap/css/bootstrap.css" />
  <style>
    table thead tr th {
      text-align: center;
    }

    table tbody tr td {
      text-align: center;
      vertical-align: middle !important;
    }

    .lx {
      width: 55px;
      font-size: 16px;
      text-align: center;
      vertical-align: auto;
      line-height: 16px;
      height: 35px;
      padding: 0;
    }

    table {

      overflow: scroll;
    }
  </style>
  <link rel="stylesheet" href="./Nprogress/Nprogress.css">
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-xs-6">
        <hr />
        <!-- 1 输入框和按钮 -->
        <form action="" id="searchFrom">
        <div class="input-group">
          <input id="searchBookName" type="text" class="form-control" placeholder="请输入要寻找的书名" />
          <span class="input-group-btn">
              <button id="searchBtn" class="btn btn-default" type="button">
                搜索
              </button>
          </span>
          
        </div>
      </form>
        <hr />

        <!-- 2 列表 -->
        <table class="table table-bordered table-striped">
          <thead>
            <tr>
              <th>id</th>
              <th>书名</th>
              <th>作者</th>
              <th>出版社</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
      </div>
      <div class="col-xs-6">
        <hr />
        <form autocomplete="off">
          <div class="form-group">
            <label for="bookname">书名</label>
            <input type="text" class="form-control" id="bookname" placeholder="请输入书名" />
          </div>

          <div class="form-group">
            <label for="author">作者</label>
            <input type="text" class="form-control" id="author" placeholder="请输入作者" />
          </div>

          <div class="form-group">
            <label for="publisher">出版社</label>
            <input type="text" class="form-control" id="publisher" placeholder="请输入出版社" />
          </div>

          <button type="submit" class="btn btn-success">添加</button>
        </form>
      </div>
    </div>
  </div>

  <!-- 修改面板 -->
  <!-- 首先我们使用bootstrap来搭建页面，我们要一个模态框 一个修改按钮-->

  <!-- a按钮 需要绑定对应的id 修改我们自己需要的样式 加上一个我们自己的类名-->
  <!-- 把按钮加到tbody里面 -->
  <!-- 模态框 -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <!-- 把输入框放入一个表单内 -->
        <form action="" id="updateForm">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">修改数据</h4>
          </div>
          <div class="modal-body">
            <!-- 这里我们等下需要输入框 -->
            <div class="input-group">
              <input type="hidden" class="form-control" name="id" aria-describedby="basic-addon1">
              <!-- 改为隐藏框 -->
            </div>

            <div class="input-group">
              <span class="input-group-addon" id="basic-addon1">书名</span>
              <input type="text" class="form-control" name="bookname" aria-describedby="basic-addon1">
            </div>

            <div class="input-group">
              <span class="input-group-addon" id="basic-addon1">作者</span>
              <input type="text" class="form-control" name="author" aria-describedby="basic-addon1">
            </div>

            <div class="input-group">
              <span class="input-group-addon" id="basic-addon1">出版社</span>
              <input type="text" class="form-control" name="publisher" aria-describedby="basic-addon1">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            <button type="button" class="btn btn-primary updateLx">提交修改</button>
          </div>
        </form>
      </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->
  <!-- 修改面板结束 -->
  <!-- 2 先引入jquery.js -->
  <script src="./lib/jquery.js"></script>
  <!-- 3 引入 bootstrap.js -->
  <script src="./lib/bootstrap/js/bootstrap.js"></script>

  <!-- 4 引入 axios -->
  <script src="./lib/axios.js"></script>
  <script src="./Nprogress/Nprogress.js"></script>
  <!-- 5 内部js 编写业务 -->
  <script>
    //获取杂七杂八的数据
    const tbody = document.querySelector("tbody");
    const searchBtn = document.querySelector("#searchBtn");
    const searchInput = document.querySelector("#searchBookName");
    const addbtn = document.querySelector(".btn-success");
    const form = document.querySelector("form");
    
    axios.defaults.baseURL=`http://www.itcbc.com:3006`;

    //请求拦截器
    axios.interceptors.request.use(config => {
      // Do something before request is sent
      NProgress.start();
      return config;
    }, error => {
      // Do something with request error
      return Promise.reject(error);
    });
    //响应拦截器
    axios.interceptors.response.use(response => {
      // Do something before response is sent
      NProgress.done();
      return response;
    }, error => {
      // Do something with response error
      NProgress.done();
      return Promise.reject(error);
    });
    form.addEventListener("submit", (e) => {
      e.preventDefault();
      form.reset();
    })

    //查询
    searchBtn.addEventListener("click", () => {
      xuanRan();
      document.querySelector("#searchFrom").reset();
    })
    //添加
    addbtn.addEventListener("click", (e) => {
      const bookname = document.querySelector("#bookname").value.trim();
      const author = document.querySelector("#author").value.trim();
      const publisher = document.querySelector("#publisher").value.trim();
    
      axios({
        method: 'post',
        url: `/api/addbook`,
        data: {
          bookname,
          author,
          publisher,
          appkey: "liuxin"
        }
      }).then(result => {
        if (result.data.status === 0) {
          alert("添加成功啦")
          xuanRan();
        } else {
          alert("失败");
        }
      })
    })
    //删除
    tbody.addEventListener("click", (e) => {
      if (e.target.classList.contains("deleteBtn")) {
        let flag = confirm("你是否要删除");
        console.log(e.target.dataset.id)
        if (flag) {
          axios({
            method: 'delete',
            url: `/api/delbook`,
            params: {
              id: e.target.dataset.id,
              appkey: "liuxin",
            }
          }).then(reulst => {
            if (reulst.data.status === 0) {
              alert("删除成功啦")
              xuanRan(searchInput.value.trim());
            } else {
              alert("失败");
            }
          })
        }
      }
      //现在我们开始js的书写。现在是模态框能出来，但是我们拿不到数据，所以我们需要吧表格的数据渲染到表单
      //判断我们点击的是否是修改
      if (e.target.classList.contains("lx")) {
        //获取点击的元素的id
        const id = e.target.dataset.id;//这里获取id
        console.log(id);
        //通过id拿数据
        axios({
          method: 'get',//获取用get
          url: `/api/getbooks`,
          params: {
            id,//对象的简写方式
            appkey: "liuxin",//秘钥
          }
        }).then(result => {
          //拿到数据后，我们进行表单渲染
          //先把数据转换为一个对象；
          const obj = result.data.data[0];
          console.log(obj);
          //遍历
          for (const key in obj) {
            //每一个输入框的value等于对象的属性值
            document.querySelector(`input[name=${key}]`).value = obj[key];
          }
        })
      }

    })
    xuanRan();
    //渲染
    //修改
    // 接下来获取提交按钮完成修改
    const updateLx = document.querySelector(".updateLx");
    updateLx.addEventListener("click", (e) => {
      //拿表单的数据，因为更新需要所有的表单数据作为参数、、这里我们用jq的表单的快捷获取
      const str = $("#updateForm").serialize();//作为id选择器我们要加#
      console.log(str);
      //我们拿到数据后就可以修改了
      axios({
        method: 'put',
        url: `/api/updatebook`,
        data: str + `&appkey=liuxin`//这里用data的其他写法，拼接写法，不用键值对的写法了，因为都是密钥数据，所以我们要加上密钥
      }).then(result => {
        console.log(result);
        //每次修改后我们要关闭我们的模态框,而且要重新渲染页面
        $('#myModal').modal('hide');
        xuanRan();
      })
    })
    function xuanRan() {
      function getName(bookname = "") {
        let query = "";
        if (bookname) {
          query = `&bookname=${bookname}`;
        }
        console.log(query)
        return query;
      }
      axios({
        method: 'get',
        url: `/api/getbooks?appkey=liuxin` + getName(searchInput.value.trim()),
      }).then(result => {
        let trHTML = result.data.data.sort((a, b) => a.id - b.id).reduce((h, v, i) => {
          return h + `
                               <tr>
                                 <td>${v.id}</td>
                                 <td>${v.bookname}</td>
                                 <td>${v.author}</td>
                                 <td>${v.publisher}</td>
                                 <td>
                                  <button type="button" class="deleteBtn btn btn-danger" data-toggle="modal" data-id="${v.id}" data-target=".bs-example-modal-lg">删除</button>
                                  <button type="button" class="btn btn-primary btn-lg lx"  data-id="${v.id}" data-toggle="modal" data-target="#myModal">
                                     修改
                                     </button>
                                </td>
                                </tr>

                               `
        }, "");//给他加上一个id，方便我们后期取值；
        tbody.innerHTML = trHTML;
      })
    }
  </script>
</body>

</html>